// packageJ/anytime_service/my/index/index.js
const app = getApp();
import Dialog from '../../../../dist/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    authtrue: 1,//角色申请
    is_publish: 1,//发布者：1是0否
    is_shifu: 0,//师傅：1是0否
    is_enterprise: 0,//企业：1是0否
    is_area_agent: 1,//是否区域管理员：1是0否
    is_shop:0,//是否平台管理员
    member: {},
    imgPath: app.globalData.imgPath,
    msgShow:false,
    tempArray:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData()
    this.getTemplate();
  },
  getData() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.be-within-call.frontend.manage.my'),
      success: resdata => {
        let { result, data, msg } = resdata.data;
        if (result) {
          this.setData({
            member: data.member,
            is_publish: data.is_publish,
            is_shifu: data.is_shifu,
            is_enterprise: data.is_enterprise,
            is_area_agent: data.is_area_agent,
            is_shop: data.is_shop,
          })
        } else {
          app.tips(msg);
        }
      }
    })
  },
  msgtempClick() {
    this.getTemplate(true);
  },
  closeMsg() {
    this.setData({
      msgShow:false,
    });
    app.globalData.informMyShow = true;
  },
  tempSetting() { //查询订阅消息
    wx.getSetting({
      withSubscriptions: true,
      success:(res) => {
        this.getSettingData(res);
      },
      fail:(err) => {
        // resolve(false);

        console.log('getSetting',err);
      },
    });
    
  },
  getSettingData(res) {
    let mainSwitch = res.subscriptionsSetting?.mainSwitch;
    //检查订阅消息的设置是否关闭
    if(!mainSwitch) {
      this.modeSetting();
    }
    let itemSettings = res.subscriptionsSetting?.itemSettings;
    // 检查是否有订阅消息设置
    if ((!itemSettings && this.data.is_shop) || (!itemSettings && this.data.is_publish)) {
      if(!app.globalData.informMyShow) {
        this.setData({
          msgShow: true
        });
      }
      return;
    }
    // 获取消息模板对象
    const identityObj = this.data.tempArray['technician_identity_examine_shop'];
    const skillObj = this.data.tempArray['technician_skill_examine_shop'];
    const userObj = this.data.tempArray['order_refund_user'];

    // 获取已订阅的消息模板ID
    const subscribedTemplateIds = Object.keys(itemSettings);

        

      // 检查身份相关的消息模板
    if(this.data.is_shop) {
        this.checkSubscription(subscribedTemplateIds,identityObj, this.data.is_shop);
        this.checkSubscription(subscribedTemplateIds,skillObj, this.data.is_shop);
    }
    if(this.data.is_publish) {
      this.checkSubscription(subscribedTemplateIds,userObj, this.data.is_publish);
    }
  },
  // 检查每个消息模板的订阅状态
  checkSubscription(tempArray,templateObj, condition) {
    if (
      !tempArray.includes(templateObj.template_id) &&
      templateObj.is_open && 
      condition
    ) {
      if(!app.globalData.informMyShow ) {
        this.setData({
          msgShow: true
        });
      }
    } else {
      //查询订阅消息授权状态，未授权，累加发送订阅消息
      if(!templateObj.authorize && tempArray.includes(templateObj.template_id) && templateObj.is_open) {
        this.setData({
          msgShow: true
        });
      } 
      
    }
  },
  goto(e) {
    let url = e.currentTarget.dataset.url;
     if (url == 'Demand') {
      let type = e.currentTarget.dataset.type;
      wx.navigateTo({
        url: `/packageJ/anytime_service/my/${url}/${url}?type=${type}`,
      })
    } else if (url=='skill_order') {
      wx.navigateTo({
        url: '/packageJ/anytime_service/my/skill_order/skill_order?order_type=1',
      })
    }else if(url == 'area_order'){
      wx.navigateTo({
        url: '/packageJ/anytime_service/my/skill_order/skill_order?order_type=2',
      })
    }else if(url=='master_worker'){
      let params = e.currentTarget.dataset.params;
      wx.navigateTo({
        url: `/packageJ/anytime_service/my/role_apply_for/${url}/${url}?apply_type=${params}`,
      })
    }else if(url=='skill_manage'||url=='DemandManage'){
      wx.navigateTo({
        url: `/packageJ/anytime_service/my/${url}/${url}`,
      })
    }else if(url=='promulgator'){
      let role = e.currentTarget.dataset.role;
      wx.navigateTo({
        url: '/packageJ/anytime_service/my/role_apply_for/promulgator/promulgator?role='+role
      })
    }else if(url == 'area_manage'){
     
      wx.navigateTo({
        url: '/packageJ/anytime_service/my/area_manage/area_manage',
      })
    }else if(url=='enterprise_info'){
      wx.navigateTo({
        url: '/packageJ/anytime_service/enterprise_application/index/index'
      })
    }else if(url=='enterprise_publish'){
      wx.navigateTo({
        url: '/packageJ/anytime_service/enterprise_application/demand_publish/index'
      })
    }else if(url=='demand_management'){
      wx.navigateTo({
        url: '/packageJ/anytime_service/enterprise_application/demand_management/index'
      })
    }else if(url=='enterprise_package'){
      wx.navigateTo({
        url: '/packageJ/anytime_service/enterprise_application/enterprise_package/index'
      })
    }else if(url=='order_manage'){
     
      wx.navigateTo({
        url: '/packageJ/anytime_service/order/index/index'
      })
    }else if(url=='record'){
      wx.navigateTo({
        url: '/packageJ/anytime_service/record/index',
      })
    }else {
      wx.navigateTo({
        url: `/packageJ/anytime_service/my/role_apply_for/${url}/${url}`,
      })
    }
  },
  
  //平台：（指定1个或多个人接收通知）
  //技师身份审核（平台）
  //技师技能审核（平台）
  //订单退款通知（失效订单退款通知）(用户)
  //获取模板ID
  getTemplate(type) {
    let urlStr = app.getNetAddresss("plugin.be-within-call.frontend.notice-template");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          let array = [];
          for(let key in data) {
            if((data[key].key == 'technician_identity_examine_shop' ||  data[key].key == 'technician_skill_examine_shop') && this.data.is_shop) {
              if(data[key].is_open) {
                array.push(data[key].template_id);
              }
            }
            if(data[key].key  == 'order_refund_user' && this.data.is_publish){
              if(data[key].is_open) {
                array.push(data[key].template_id);
              }
            }
            
          }
          this.setData({
            TemplateArray: array,
            tempArray:data,
          });
          if(type) {
            wx.requestSubscribeMessage({
              tmplIds: this.data.TemplateArray,
              success: (res) => {
                let tempArray = [];
                for(let key in data) {
                  if(res[data[key].template_id] == 'accept') {
                    tempArray.push(data[key].key)
                  }
                }
                this.setData({
                  msgShow:false,
                })
                this.setTempLog(tempArray);
              },
              fail: (err) => {
                console.log(err);
                this.setData({
                  msgShow:false,
                })
              },
            });
          } else {
            this.tempSetting();
          }
          
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  setTempLog(tempArray) {
    let urlStr = app.getNetAddresss("plugin.be-within-call.frontend.notice-template.save-log");
    app._postNetWork({
      url: urlStr,
      data:{template_keys:tempArray},
      success: resdata => {
        let { result, data, msg } = resdata.data;
        if (result) {
          app.tips(msg);
        } else {
          app.tips(msg);
        }
      }
    })
  },
  modeSetting() {
    Dialog.confirm({
      message: '是否打开设置页',
    })
    .then(() => {
      // on confirm
      wx.openSetting({
        withSubscriptions:true,
        success (res) {
          let mainSwitch = res.subscriptionsSetting?.mainSwitch;
          if(mainSwitch) {
            wx.showToast({
              icon: "none",
              title: "获取订阅消息权限成功",
              duration: 1500,
            });
          } else {
            wx.showToast({
              icon: "none",
              title: "获取订阅消息权限失败",
              duration: 1500,
            });
          }
        }
      })
      
    })
    .catch(() => {
      // on cancel
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})